package main

import (
	"backenddev/no2/gin_project2/models"
	"backenddev/no2/gin_project2/nets"
	"errors"

	"github.com/gin-gonic/gin"
)

func main() {
	r := gin.Default()

	// 中间件：打印请求路径
	r.Use(func(c *gin.Context) {
		println("请求路径:", c.Request.URL.Path)
		c.Next()
	})

	// 路由1：获取所有用户（成功场景）
	r.GET("/api/users", func(c *gin.Context) {
		users := mockGetAllUsers()
		if len(users) == 0 {
			nets.Success(c, users)
			return
		}
		nets.Success(c, users) // 返回用户数组
	})

	// 路由2：查询失败（无数据或错误）
	r.GET("/api/users/error", func(c *gin.Context) {
		users, err := mockGetUsersWithError()
		if err != nil {
			nets.Fail(c, 500, "数据库查询失败")
			return
		}
		if len(users) == 0 {
			nets.Fail(c, 404, "暂无用户数据")
			return
		}
		nets.Success(c, users)
	})

	// 路由3：带查询参数的用户搜索
	r.GET("/api/users/search", func(c *gin.Context) {
		keyword := c.Query("keyword")
		if keyword == "" {
			nets.Fail(c, 400, "搜索关键词不能为空")
			return
		}

		allUsers := mockGetAllUsers()
		var filtered []models.User
		for _, user := range allUsers {
			if user.UserName == keyword {
				filtered = append(filtered, user)
			}
		}

		if len(filtered) == 0 {
			nets.Success(c, []models.User{}) // 返回空数组，表示“未找到”
		} else {
			nets.Success(c, filtered)
		}
	})
	println("服务启动：http://localhost:8080")
	r.Run(":8080")
}

func mockGetAllUsers() []models.User {
	// 模拟从数据库读取数据
	return []models.User{
		{Uid: 1, UserName: "alice", Email: "alice@example.com", CreatedAt: "2025-09-16"},
		{Uid: 2, UserName: "bob", Email: "bob@example.com", CreatedAt: "2025-09-16"},
		{Uid: 3, UserName: "charlie", Email: "charlie@example.com", CreatedAt: "2025-09-16"},
	}
}

func mockGetUsersWithError() ([]models.User, error) {
	return nil, errors.New("database connection failed")
}
